﻿using Goooodbye.Core.Entities;
using Goooodbye.Core.Services;
using System;
using System.Windows.Forms;

namespace Goooodbye.Presentation.WinFormsApp
{
    public partial class FormDictionaryEdit : FormBase
    {
        private IDictService dictService;
        public Dict Entity { get; set; }

        public FormDictionaryEdit(IDictService dictService)
        {
            InitializeComponent();
            this.dictService = dictService;
        }

        private void FormDictionaryEdit_Load(object sender, EventArgs e)
        {
            if (Entity != null)
            {
                this.txtTerm.Text = Entity.Term;
                this.txtMapping.Text = Entity.Mapping;
                this.txtNote.Text = Entity.Note;
            }
            else
            {
                this.Entity = new Dict();
            }
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (InputValidate())
            {
                Save();
            }
            else
            {
                this.DialogResult = DialogResult.None;
            }
        }

        private bool InputValidate()
        {
            bool ret = true;
            var term = this.txtTerm.Text.Trim();
            var mapping = this.txtMapping.Text.Trim();

            if (String.IsNullOrEmpty(term))
            {
                this.errTerm.SetError(this.txtTerm, "请输入词条");
                ret = false;
            }
            else
            {
                this.errTerm.Clear();
            }


            if (String.IsNullOrEmpty(mapping))
            {
                this.errMapping.SetError(this.txtMapping, "请输入转换为的内容");
                ret = false;
            }
            else
            {
                this.errMapping.Clear();
            }
            return ret;
        }

        private void Save()
        {
            Entity.Term = this.txtTerm.Text.Trim();
            Entity.Mapping = this.txtMapping.Text.Trim();
            Entity.Note = this.txtNote.Text.Trim();
            if (!dictService.Save(Entity))
            {
                if (MessageBox.Show("保存时发生异常", "错误", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == DialogResult.Retry)
                {
                    Save();
                }
            }
        }
    }
}
